/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.dao;

import cn.easyplatform.entities.beans.table.TableField;
import cn.easyplatform.lang.Lang;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public abstract class Dialect {

    /**
     * 根据提供的sql、分页参数：start、pagesize获取分页后的sql语句
     *
     * @param sql      未分页sql语句
     * @param page   当前页数
     * @return
     */
    public String getPageSql(String sql, Page page) {
        StringBuilder sb = new StringBuilder(sql.length() + 100);
        sb.append(getPageBefore(page));
        sb.append(sql);
        sb.append(getPageAfter(page));
        return sb.toString();
    }

    /**
     * 根据提供的sql、分页参数：start、pagesize获取分页sql语句before字符串
     *
     * @param page   当前页数
     * @return
     */
    protected abstract String getPageBefore(Page page);

    /**
     * 根据提供的sql、分页参数：start、pagesize获取分页sql语句after字符串
     *
     * @param page   当前页数
     * @return
     */
    protected abstract String getPageAfter(Page page);

    /**
     * 获取数据类型
     *
     * @param mf
     * @return
     */
    public String evalFieldType(TableField mf) {
        switch (mf.getType()) {
            case CHAR:
                return "CHAR(" + mf.getLength() + ")";

            case BOOLEAN:
                return "BOOLEAN";

            case VARCHAR:
                return "VARCHAR(" + mf.getLength() + ")";

            case CLOB:
                return "TEXT";

            case OBJECT:
            case BLOB:
                return "BLOB";

            case DATETIME:
                return "datetime";

            case DATE:
                return "datetime";
            case TIME:
                return "TIME";
            case LONG:
            case INT:
                // 用户自定义了宽度
                if (mf.getLength() > 0)
                    return "INT(" + mf.getLength() + ")";
                // 用数据库的默认宽度
                return "INT";

            case NUMERIC:
                // 用户自定义了精度
                if (mf.getLength() > 0 && mf.getDecimal() > 0) {
                    return "NUMERIC(" + mf.getLength() + "," + mf.getDecimal()
                            + ")";
                }
                return "NUMERIC(15,2)";
            default:
                throw Lang.makeThrow("Unsupport colType '%s' of field '%s' ",
                        mf.getType(), mf.getName());
        }
    }

    public String evalField(String field) {
        return "COLUMN " + field;
    }
}
